package com.t194.config;


import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.io.IOException;

@Configuration
@PropertySource("classpath:db.properties")
//mapper层扫描仪
@MapperScan(basePackages = "com.t194.mapper")
//service层扫描仪
@ComponentScan(basePackages = {"com.t194.service","com.t194.config","com.t194.util"})
//事务驱动
@EnableTransactionManagement
//注解AOP驱动
@EnableAspectJAutoProxy
public class ApplicationConfig  {

    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;


    //    解析注解
    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer (){
        PropertySourcesPlaceholderConfigurer configurer=new PropertySourcesPlaceholderConfigurer();
        return configurer;
    }

    //   读取建立连接
    @Bean(destroyMethod ="close")
    public DruidDataSource dataSource(){
        DruidDataSource dataSource=new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
    //    加载mybatis的配置文件和映射文件
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        ResourcePatternResolver resolver =new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setConfigLocation(resolver.getResource("classpath:mybatis-config.xml"));
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:mapper/*.xml") );
        return sqlSessionFactoryBean;
    }
    //事务config
    @Bean
    public DataSourceTransactionManager transactionManager(){
        DataSourceTransactionManager transactionManager=new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource());
        return transactionManager;

    }
}
